package InternetCode.Socket.Exa7;


import java.io.*;
import java.net.*;

/**
 * 通过服务器套接字接收客户端发送的信息
 * 注意: 实例Demo都是单端通信测试的
 */
public class ServerSocketFrame {

    // 声明BufferedReader对象,用来接收消息
    private BufferedReader reader;
    // 声明ServerSocket对象
    private ServerSocket server;
    // 声明Socket对象socket
    private Socket socket;

    public void getServer() {
        try {
            // 实例化Socket对象
            server = new ServerSocket(1978);
            System.out.println("服务器套接字已经创建成功\n");
            while (true) {
                System.out.println("等待客户机的连接......\n");
                // 等待连接获得Socket对象
                socket = server.accept();
                System.out.println("连接成功。\n");
                //获得客户端通讯输入流
                reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                //监听客户端通信输入流
                getClientInfo();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getClientInfo() {
        try {
            while (true) {
                String str = reader.readLine();
                if(str==null) str = reader.read()+"";
                if(str.equals("-1")) {
                    System.out.println("客户端断开连接");
                    break;
                }
                System.out.println("接收到客户端发送的消息："+str + "\n"); // 获得客户端信息
            }
        } catch (Exception e) {
            //打印异常消息
            e.printStackTrace();
            System.out.println("客户端已退出。\n");
        } finally {
            try {
                if (reader != null) {
                    // 关闭流
                    reader.close();
                }
                if (socket != null) {
                    // 关闭套接字
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        ServerSocketFrame frame = new ServerSocketFrame();
        frame.getServer();
    }

   
}